package com.ruicar.afs.cloud.contract.gateway.processor.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruicar.afs.cloud.common.core.dynamicrequest.DynamicRequest;
import com.ruicar.afs.cloud.common.core.holder.TransRequestContextHolder;
import com.ruicar.afs.cloud.common.modules.enums.SystemType;
import com.ruicar.afs.cloud.contract.gateway.beans.SystemDefine;
import com.ruicar.afs.cloud.contract.gateway.components.ProcessorCache;
import com.ruicar.afs.cloud.contract.gateway.entity.GateWaySystemMapping;
import com.ruicar.afs.cloud.contract.gateway.enums.ApiStatus;
import com.ruicar.afs.cloud.contract.gateway.enums.RequestType;
import com.ruicar.afs.cloud.contract.gateway.processor.ProcessorHelper;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

@Builder
@Slf4j
public class RequestRunner implements Runnable{
    private final CountDownLatch countDownLatch;
    private final DynamicRequest dynamicRequest;
    private final JSON params;
    private final JSONObject jsonObject;
    private final SystemType systemType;
    private final SystemDefine systemDefine;
    private final TransRequestContextHolder.SystemClientInfo systemClientInfo;
    private final TransRequestContextHolder.TransLogHeader transLogHeader;
    @Override
    public void run() {
        try {
            jsonObject.put("_requestError",JSONUtil.createArray());
            TransRequestContextHolder.bindSysClientInfo(systemClientInfo);
            TransRequestContextHolder.bindTransHeader(transLogHeader);
            process();
        }catch (Exception e){
            log.error("",e);
        }finally {
            countDownLatch.countDown();
            TransRequestContextHolder.clear();
        }
    }


    private void process(){
        String result=null;
        if(systemDefine.getGateWaySystemMapping().getStatus()==ApiStatus.MOCK){
            result = systemDefine.getGateWaySystemMapping().getMockJson();
            log.info("当前请求接口===>[{}],接口处于mock状态返回mock数据", systemDefine.getGateWaySystemMapping().getTargetUrl());
        }else {
            log.info("当前请求接口===>[{}],系统类型[{}]", systemDefine.getGateWaySystemMapping().getTargetUrl(), systemDefine.getGateWaySystemMapping().getSystemType());
            GateWaySystemMapping gateWaySystemMapping = systemDefine.getGateWaySystemMapping();
            JSON systemRequestJson = ProcessorHelper.genDeepRequestParam(params, systemDefine.getParamInMappings());
            List<String> extParams = StrUtil.splitTrim(systemDefine.getGateWaySystemMapping().getExtParams(), ";");
            List<String> extHeaders = StrUtil.splitTrim(systemDefine.getGateWaySystemMapping().getExtHeaders(), ";");

            for (String string : extParams) {
                String[] strings = string.split("=");
                if (strings.length == 2) {
                    JSONUtil.putByPath(systemRequestJson, strings[0], strings[1]);
                }
            }

            Map<String, List<String>> headers = new HashMap<>(8);
            for (String string : extHeaders) {
                String[] strings = string.split("=");
                if (strings.length == 2) {
                    headers.put(strings[0], StrUtil.splitTrim(strings[1], ","));
                }
            }
            if (gateWaySystemMapping.getTargetUrl().startsWith("lb://")) {
                String targetUri = gateWaySystemMapping.getTargetUrl().replaceFirst("lb://", "");
                String serviceName = targetUri.substring(0, targetUri.indexOf(StrUtil.SLASH));
                String requestUri = targetUri.substring(targetUri.indexOf(StrUtil.SLASH));
                requestUri = ProcessorHelper.genRequestUri(params, requestUri);
                log.info("处理后的Uri为[{}],请求类型为{}", requestUri, gateWaySystemMapping.getRequestMethod());
                try {
                    if (RequestType.GET == gateWaySystemMapping.getRequestMethod()) {
                        Map<String, String> requestParam = ProcessorHelper.convertJsonToMap(systemRequestJson);
                        log.info("处理后的参数===>请求uri[{}]，目标系统[{}],参数为[{}]", gateWaySystemMapping.getTargetUrl(), gateWaySystemMapping.getSystemType(), requestParam);
                        result = dynamicRequest.get(serviceName, requestUri, requestParam);
                    } else if (RequestType.POST == gateWaySystemMapping.getRequestMethod()) {
                        log.info("处理后的参数===>请求uri[{}]，目标系统[{}],参数为[{}]", gateWaySystemMapping.getTargetUrl(), gateWaySystemMapping.getSystemType(), systemRequestJson);
                        result = dynamicRequest.post(serviceName, requestUri, systemRequestJson);
                    } else {
                        log.warn("不支持的请求方式,系统配置ID[{}],请求URI[{}]", gateWaySystemMapping.getId(), gateWaySystemMapping.getTargetUrl());
                    }
                } catch (Exception e) {
                    log.error("", e);
                    result = "request error";
                }
            } else {
                String requestUri = gateWaySystemMapping.getTargetUrl();
                requestUri = ProcessorHelper.genRequestUri(params, requestUri);
                HttpResponse httpResponse = null;
                log.info("处理后的Uri为[{}],请求类型为{}", requestUri, gateWaySystemMapping.getRequestMethod());
                try {
                    if (RequestType.GET == gateWaySystemMapping.getRequestMethod()) {
                        Map<String, Object> requestParam = ProcessorHelper.convertJsonToObjectMap(systemRequestJson);
                        log.info("处理后的参数===>请求uri[{}]，目标系统[{}],参数为[{}]", gateWaySystemMapping.getTargetUrl(), gateWaySystemMapping.getSystemType(), requestParam);
                        httpResponse = HttpUtil.createGet(requestUri).header(headers).form(ProcessorHelper.convertJsonToObjectMap(systemRequestJson)).execute();
                    } else if (RequestType.POST == gateWaySystemMapping.getRequestMethod()) {
                        log.info("处理后的参数===>请求uri[{}]，目标系统[{}],参数为[{}]", gateWaySystemMapping.getTargetUrl(), gateWaySystemMapping.getSystemType(), systemRequestJson);
                        httpResponse = HttpUtil.createPost(requestUri).header(headers).body(systemRequestJson).execute();
                    } else {
                        log.warn("不支持的请求方式,系统配置ID[{}],请求URI[{}]", gateWaySystemMapping.getId(), gateWaySystemMapping.getTargetUrl());
                    }
                } catch (Exception e) {
                    log.error("", e);
                }
                if (httpResponse == null || httpResponse.getStatus() != 200) {
                    result = "server error";
                } else {
                    result = httpResponse.body();
                }
            }
        }

        if(JSONUtil.isJson(result)&&ProcessorHelper.checkRequest(JSONUtil.parse(result),systemDefine.getGateWaySystemMapping())){
            Assert.isTrue(StringUtils.isNotEmpty(systemDefine.getGateWaySystemMapping().getResponseAlias()), MessageFormat.format("数据接口,ID [{0}]别名为空",systemDefine.getGateWaySystemMapping().getId()));
            jsonObject.putByPath(systemDefine.getGateWaySystemMapping().getResponseAlias(),JSONUtil.parse(result));
        }else{
            jsonObject.getJSONArray("_requestError").add(systemDefine.getGateWaySystemMapping().getId());
            log.info("获取接口[{}]数据失败,系统类型[{}]，接口返回值[{}]",systemDefine.getGateWaySystemMapping().getTargetUrl(),systemDefine.getGateWaySystemMapping().getSystemType(),result);
        }
        if(StringUtils.isNoneEmpty(systemDefine.getGateWaySystemMapping().getResultConvert())) {
            ProcessorCache.getResultProcessor(systemDefine.getGateWaySystemMapping().getResultConvert()).convert(systemDefine, jsonObject);
        }
    }
}
